package com.mg.framework.kernel;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;

public class MenuController extends Actor implements Touchable {

	private Paint p = null;

	private enum Command {
		down, none
	}

	private int BUTTONWIDTH = 0;
	private Rect rect = null;

	private int pointerIndex = -1;
	private int pointerId = -1;
	private int currentPointerId = -1;

	private Command command = Command.none;
	private Command commandState = Command.none;

	public MenuController(Screen screen, Bitmap bitmap) {
		super(screen, bitmap);

		p = new Paint();
		p.setColor(Color.YELLOW);
		this.BUTTONWIDTH = bitmap.getWidth();
		this.setX(this.screen.width - 90);
		this.setY(this.screen.height - this.height);

		rect = new Rect((int) (this.getX()), (int) (this.getY()),
				(int) (this.getX() + this.BUTTONWIDTH),
				(int) (this.getY() + this.BUTTONWIDTH));
	}

	private String s = "";

	@Override
	public void gameUpdate() {
		if (this.commandState == Command.down) {
			s = "down";
		} else if (this.commandState == Command.none) {
			s = "none";
		}
	}

	@Override
	public void screenUpdate(Canvas canvas) {
		canvas.drawText(s, 200, 130, p);
		this.drawSelf(canvas, null);
	}

	@Override
	public void onTouchEvent(MotionEvent event) {
		if (this.command == Command.down) {
			commandState = Command.down;
		} else if (this.command == Command.none) {
			commandState = Command.none;
		}

	}

	@Override
	public boolean isTouched(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_POINTER_DOWN:
			if (this.currentPointerId == -1) {
				this.pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
				if (this.isInArea((int) event.getX(this.pointerIndex),
						(int) event.getY(this.pointerIndex))) {
					this.pointerId = event.getPointerId(pointerIndex);
					this.currentPointerId = pointerId;
					return true;
				}
				return false;
			}
			return false;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			if (this.currentPointerId != -1) {
				this.pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
				this.pointerId = event.getPointerId(pointerIndex);
				if (this.currentPointerId == this.pointerId) {
					this.currentPointerId = -1;
					this.command = Command.none;
					return true;
				}
				return false;
			}
			return false;
		}
		return false;
	}

	private boolean isInArea(int cx, int cy) {
		if (this.rect.contains(cx, cy)) {
			this.command = Command.down;
			return true;
		} else {
			this.command = Command.none;
			return false;
		}
	}
}
